package com.neusoft.yiyang.auth.util;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.awt.image.BufferedImage;
import java.util.Properties;

/**
 * 图形验证码生成器
 */
@Component
public class CaptchaGenerator {

    private final DefaultKaptcha defaultKaptcha;

    public CaptchaGenerator(@Value("${captcha.width:150}") int width,
                            @Value("${captcha.height:50}") int height,
                            @Value("${captcha.char.length:5}") int charLength,
                            @Value("${captcha.font.size:40}") int fontSize) {
        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width", String.valueOf(width));
        properties.setProperty("kaptcha.image.height", String.valueOf(height));
        properties.setProperty("kaptcha.textproducer.char.length", String.valueOf(charLength));
        properties.setProperty("kaptcha.textproducer.font.size", String.valueOf(fontSize));
        properties.setProperty("kaptcha.noise.impl", "com.google.code.kaptcha.impl.NoNoise");
        properties.setProperty("kaptcha.obscurificator.impl", "com.google.code.kaptcha.impl.WaterRipple");
        properties.setProperty("kaptcha.textproducer.font.names", "Arial, Courier");
        properties.setProperty("kaptcha.textproducer.char.string", "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");

        Config config = new Config(properties);
        this.defaultKaptcha = new DefaultKaptcha();
        this.defaultKaptcha.setConfig(config);
    }

    /**
     * 生成验证码文本
     *
     * @return 验证码文本
     */
    public String generateText() {
        return defaultKaptcha.createText();
    }

    /**
     * 生成验证码图片
     *
     * @param captchaText 验证码文本
     * @return 验证码图片
     */
    public BufferedImage generateImage(String captchaText) {
        return defaultKaptcha.createImage(captchaText);
    }
}
